package com.doudou.dubbo.demo;

import com.doudou.dubbo.demo.api.GreetingService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.RpcContext;

/**
 * 客户端通过java.util.concurrent.Future#get()异步调用。
 * @author zhaozw
 * @version 1.0
 * @date 2025-07-14 17:02
 **/
public class ApiAsyncConsumer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建引用实例，并设置属性
        ReferenceConfig<GreetingService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setApplication(new ApplicationConfig("first-dubbo-consumer"));
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        referenceConfig.setInterface(GreetingService.class);
        referenceConfig.setTimeout(5000);
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dubbo");

        // 设置为异步
        referenceConfig.setAsync(true);

        // 直接返回null
        GreetingService greetingService = referenceConfig.get();
        RpcContext.getContext().setAttachment("company", "juzi");
        System.out.println("sayHello -------------------->>>   "+ greetingService.sayHello("world"));

        // 等待异步返回结果
        Future<Object> future = RpcContext.getContext()
                .getFuture();
        // get()方法会阻塞线程，知道获取到结果
        System.out.println("future -------------------------->>> " + future.get());
    }
}
